#install.packages('Rserve',,'http://www.rforge.net/')
library("RestRserve")
library("DBI")

source('algorithm/bartwobj.R')

app = Application$new()

app$add_get(
  path = "/health", 
  FUN = function(.req, .res) {
    .res$set_body("OK")
  })

app$add_post(
  path = "/bartwobj", 
  FUN = function(.req, .res) {
    
    # 表名
    tableName = .req$body$tableName
    # 观察变量
    columnX = .req$body$columnX
    # 组变量
    columnY = .req$body$columnY
    # 大括号位置
    y_position = as.numeric(.req$body$yPosition)
    # 杂志风格
    palette_type = .req$body$paletteType
    # 柱子宽度
    zhu_width = as.numeric(.req$body$zhuWidth)
    # 图像尺寸 宽度
    tu_width = as.numeric(.req$body$tuWidth)
    # 图像尺寸 高度
    tu_height = as.numeric(.req$body$tuHeight)
    # 填充颜色
    fill_color = as.numeric(.req$body$fillColor)
    
    result = ""
    
    re = tryCatch({
      result = bartwobj(tableName, columnX, columnY, y_position, palette_type, zhu_width, tu_width, tu_height, fill_color)
      .res$set_body(list(
        code = "200",
        result = result
      ))
    }, error = function(e) {
      .res$set_body(list(
        code = "500",
        result = "后台算法执行错误！"
      ))
    })
    
    .res$set_content_type("application/json")
  })


backend = BackendRserve$new()
backend$start(app, http_port = 8996)


